<template>
  <div id="workItemStatistics" :style="myChartStyle" class="echart"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  dicts: ['sprint_status', 'work_status', 'work_type'],
  props: {
    works: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    works: {
      handler() {
        if (this.works&&this.works.length > 0)
          this.initEchartsWorkItem();
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      myChartStyle: {float: "left", width: "100%", height: "320px"} //图表样式
    };
  },
  methods: {
    /**
     * 计算工作项分布
     */
    initEchartsWorkItem() {
      // 获取所有工作类型并计算有效类型（排除全0类型）
      console.log(this.works);
      const allWorkTypes = Array.from(new Set(this.works.map(item => item.type)));
      const validWorkTypes = allWorkTypes.filter(type => {
        // 计算该类型在所有状态下的总数
        return this.works.some(work => work.type === type)
      });

      // 生成系列数据（自动过滤无效类型）
      const worksData = this.dict.type.work_status.map(status => {
        const data = validWorkTypes.map(type =>
          this.works.filter(work =>
            work.type === type && work.status === status.value
          ).length
        );
        return {
          name: status.label,
          type: 'bar',
          stack: 'total',
          label: {
            show: true,
            formatter: ({value}) => value > 0 ? value : '' // 隐藏0值标签
          },
          emphasis: {
            focus: 'series'
          },
          data
        };
      });

      // 生成图表配置
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'}
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        yAxis: {type: 'value'},
        xAxis: {
          type: 'category',
          data: validWorkTypes.map(type => (this.dict.type.work_type.find(item => item.value === type) || {label: type}).label)
        },
        series: worksData
      };

      // 初始化图表
      echarts.init(document.getElementById('workItemStatistics')).setOption(option);
    }
  }
};
</script>

